package cn.itcast.oa.service.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

import javax.annotation.Resource;

import org.jbpm.api.ProcessDefinition;
import org.jbpm.api.ProcessDefinitionQuery;
import org.jbpm.api.ProcessEngine;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.oa.service.ProcessDefinitionService;

@Service
@Transactional
public class ProcessDefinitionServiceImpl implements ProcessDefinitionService{
	
	@Resource
    private ProcessEngine processEngine;
	
	/**
	 * 查询所有流程定义
	 */
	@Override
	public List<ProcessDefinition> findAllLatestVersions() {
		List<ProcessDefinition> all=processEngine.getRepositoryService()
		             .createProcessDefinitionQuery()
		             .orderAsc(ProcessDefinitionQuery.PROPERTY_VERSION)
		             .list();
		
		// 2，过滤出所有最新的版本
				Map<String, ProcessDefinition> map = new HashMap<String, ProcessDefinition>();
				for (ProcessDefinition pd : all) {
					map.put(pd.getKey(), pd);
				}

				return new ArrayList<ProcessDefinition>(map.values());
	}
	
	/**
	 * 删除所有版本的流程
	 */
	@Override
	public void deleteByKey(String key) {
		// 1，查询出指定key的所有版本的流程定义
	List<ProcessDefinition> list = processEngine.getRepositoryService()//
						.createProcessDefinitionQuery()//
					.processDefinitionKey(key)//
					.list();

			// 2，循环删除
			for (ProcessDefinition pd : list) {
					     processEngine.getRepositoryService().deleteDeploymentCascade(pd.getDeploymentId());
			}
		       System.out.println("====删除成功");
	}
	
    /**
     * 部署流程
     */
	@Override
	public void deploy(ZipInputStream zipInputStream) {
		// TODO Auto-generated method stub
		processEngine.getRepositoryService()
		             .createDeployment()
		             .addResourcesFromZipInputStream(zipInputStream)
		             .deploy();
	}
	
	/**
	 *查看流程图片
	 */
	@Override
	public InputStream getProcessImageResourceAsStream(String id) {
		// TODO Auto-generated method stub
		ProcessDefinition pd=processEngine.getRepositoryService()
		             .createProcessDefinitionQuery()
		             .processDefinitionId(id)
		             .uniqueResult();
		
		return processEngine.getRepositoryService().getResourceAsStream(pd.getDeploymentId(), pd.getImageResourceName());
		           
	}
}
